import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        Document doc = new Document();
        EditHistory history = new EditHistory();

        // 用户输入操作
        history.executeCommand(new AddTextCommand(doc, "Hello"));
        history.executeCommand(new AddTextCommand(doc, " World!"));
        history.executeCommand(new AddTextCommand(doc, " 你好！"));

        // 连续撤销两次
        history.undoLastCommand(); // 撤销 " 你好！"
        history.undoLastCommand(); // 撤销 " World!"
    }
}

// 1. 命令接口
interface TextCommand {
    void execute();
    void undo();
}

// 2. 具体命令：添加文字
class AddTextCommand implements TextCommand {
    private Document document;  // 接收者
    private String text;        // 操作内容
    private int position;       // 插入位置（简化场景，始终追加到末尾）

    public AddTextCommand(Document document, String text) {
        this.document = document;
        this.text = text;
        this.position = document.getContent().length(); // 记录插入位置
    }

    @Override
    public void execute() {
        document.addText(text);
    }

    @Override
    public void undo() {
        document.deleteText(position, text.length());
    }
}

// 3. 接收者：文档类
class Document {
    private StringBuilder content = new StringBuilder();

    public void addText(String text) {
        content.append(text);
        System.out.println("文档内容: " + content);
    }

    public void deleteText(int start, int length) {
        content.delete(start, start + length);
        System.out.println("撤销后内容: " + content);
    }

    public String getContent() {
        return content.toString();
    }
}

// 4. 调用者：编辑历史管理器
class EditHistory {
    private Stack<TextCommand> history = new Stack<>();

    public void executeCommand(TextCommand command) {
        command.execute();
        history.push(command);
    }

    public void undoLastCommand() {
        if (!history.isEmpty()) {
            TextCommand lastCommand = history.pop();
            lastCommand.undo();
        }
    }
}
